'use strict';
const log = require('./logger');
const deezerApi = require('deezer-request2');
/**
 * Get alternative track for a song by its track infos.
 *
 * @param {Object} trackInfos
 */
const getTrackAlternative = async (trackInfos) => {
  try {
    const { data } = await deezerApi.searchAlternative(trackInfos, 20);
    log.debug('Got alternative track for track/' + trackInfos.SNG_ID);
    if (
      data &&
      Object.keys(data.error).length === 0 &&
      data.results &&
      data.results.data &&
      data.results.data.length > 0
    ) {
      let matchingTracks = [];
      for (const foundTrack of data.results.data) {
        if (
          trackInfos.ART_ID == foundTrack.ART_ID &&
          trackInfos.ISRC == foundTrack.ISRC &&
          trackInfos.SNG_TITLE == foundTrack.SNG_TITLE &&
          Math.abs(trackInfos.DURATION - foundTrack.DURATION) <= 10
        ) {
          matchingTracks.push(foundTrack);
        }
      }

      if (matchingTracks.length > 0) {
        matchingTracks[0].SNG_TITLE_VERSION = trackInfos.SNG_TITLE_VERSION;
        return matchingTracks[0];
      } else {
        throw 'No alternative track available';
      }
    } else {
      throw 'No alternative track available';
    }
  } catch (err) {
    throw err;
  }
};

module.exports = getTrackAlternative;
